use crate::radio::{radio_group::use_radio_group, Radio};
use leptos::prelude::*;
use shq_common::prelude::Size;

#[component]
pub fn RadioItem(
    #[prop(into)] key: String,
    #[prop(optional, into)] size: MaybeProp<Size>,
    #[prop(optional, into)] disabled: MaybeProp<bool>,
    #[prop(optional)] children: Option<Children>,
) -> impl IntoView {
    let radio_group_value = use_radio_group();
    let checked = RwSignal::new(false);
    let item_key = StoredValue::new(key);

    let is_checked = Memo::new(move |_| {
        radio_group_value
            .value
            .with(|value| item_key.with_value(|key| value.as_ref() == Some(key)))
    });

    Effect::new(move |prev: Option<bool>| {
        let checked = checked.get();
        if prev.is_some() {
            if !is_checked.get_untracked() {
                radio_group_value.value.set(Some(item_key.get_value()))
            }
        }
        checked
    });
    if let Some(children) = children {
        view! {
            <Radio name=radio_group_value.name size disabled
                value=(is_checked, checked.write_only())>
                {children()}
            </Radio>
        }
    } else {
        view! { <Radio name=radio_group_value.name size disabled value=(is_checked, checked.write_only())/> }
    }
}
